//
//  SKProductsRequest+Blocks.m
//
//  Created by Alexey Aleshkov on 12.09.12.
//  Copyright (c) 2012 DzeTech. All rights reserved.
//


#import "SKProductsRequest+Blocks.h"
#import <objc/runtime.h> 


static NSString *const kSKProductsRequestSuccessBlock = @"SKProductsRequest.SuccessBlock";
static NSString *const kSKProductsRequestFailureBlock = @"SKProductsRequest.FailureBlock";


@implementation SKProductsRequest (Blocks)

+ (void)requestWithProductIdentifiers:(NSArray *)productIdentifiers successBlock:(SKProductsRequestSuccessBlock)successBlock failureBlock:(SKProductsRequestFailureBlock)failureBlock
{
	SKProductsRequest *request = [[SKProductsRequest alloc] initWithProductIdentifiers:productIdentifiers successBlock:successBlock failureBlock:failureBlock];
	[request autorelease];
	[request start];
}

#pragma mark -
#pragma mark Init / Dealloc

- (id)initWithProductIdentifiers:(NSArray *)productIdentifiers successBlock:(SKProductsRequestSuccessBlock)successBlock failureBlock:(SKProductsRequestFailureBlock)failureBlock
{
	NSSet *productIdentifiersSet = [NSSet setWithArray:productIdentifiers];

	self = [self initWithProductIdentifiers:productIdentifiersSet];
	if (!self) {
		return nil;
	}
	
	objc_setAssociatedObject(self, kSKProductsRequestSuccessBlock, successBlock, OBJC_ASSOCIATION_COPY);
	objc_setAssociatedObject(self, kSKProductsRequestFailureBlock, failureBlock, OBJC_ASSOCIATION_COPY);
	
	self.delegate = (id <SKProductsRequestDelegate>)self;

	return self;
}

#pragma mark -
#pragma mark SKProductsRequestDelegate

- (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response
{
	SKProductsRequestSuccessBlock successBlock = objc_getAssociatedObject(self, kSKProductsRequestSuccessBlock);
	if (successBlock) {
		successBlock(response, response.products);
	}
}

- (void)request:(SKRequest *)request didFailWithError:(NSError *)error
{
	SKProductsRequestFailureBlock failureBlock = objc_getAssociatedObject(self, kSKProductsRequestFailureBlock);
	if (failureBlock) {
		failureBlock(error);
	}
}

@end
